import torch
import torch.nn as nn


class AlexNetModel(nn.Module):
    def __init__(self, num_class=1000, input_channels=3, dropout=0.5):
        super(AlexNetModel, self).__init__()
        self.features = nn.Sequential(
            # [B, 3, 224, 224]
            nn.Conv2d(input_channels, 64, kernel_size=11, stride=4, padding=2),
            # [B, 64, 55, 55]
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            # [B, 64, 27, 27]

            nn.Conv2d(64, 192, kernel_size=5, padding=2),
            nn.ReLU(inplace=True),
            # [B, 192, 27, 27]
            nn.MaxPool2d(kernel_size=3, stride=2),
            # [B, 192, 13, 13]

            nn.Conv2d(192, 384, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            # [B, 384, 13, 13]

            nn.Conv2d(384, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            # [B, 256, 13, 13]

            nn.Conv2d(256, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            # [B, 256, 13, 13]
            nn.MaxPool2d(kernel_size=3, stride=2),
            # [B, 256, 6, 6]
        )
        self.classifier = nn.Sequential(
            nn.Dropout(p=dropout),
            nn.Linear(256 * 6 * 6, 4096),
            nn.ReLU(inplace=True),
            # [B, 4096]

            nn.Dropout(p=dropout),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            # [B, 4096]

            nn.Linear(4096, num_class),
            # [B, num_class]
        )

    def forward(self, x):
        # [B, 3, 224, 224]
        x = self.features(x)
        # [B, 256, 6, 6]
        x = torch.flatten(x, 1)
        # [B, 256*6*6]
        # 保持 batch 维，只展平特征部分
        x = self.classifier(x)
        # [B, num_class]
        return x
